import React, { useEffect, useRef } from 'react'
import flvjs from 'flv.js'

const FlvPlayer = ({ url, type = 'flv', controls = true }) => {
  const videoRef = useRef(null)
  const playerRef = useRef(null)

  useEffect(() => {
    if (flvjs.isSupported()) {
      const player = flvjs.createPlayer({
        type: type,
        url: url,
        isLive: true,
        hasAudio: false,
        stashInitialSize: 128,
      })

      player.attachMediaElement(videoRef.current)
      player.load()
      player.play()
      playerRef.current = player
    }

    return () => {
      if (playerRef.current) {
        playerRef.current.pause()
        playerRef.current.unload()
        playerRef.current.detachMediaElement()
        playerRef.current.destroy()
      }
    }
  }, [url, type])

  return (
    <video ref={videoRef} controls={controls} muted style={{ width: '100%' }} />
  )
}

export default FlvPlayer
